<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader :list="list" @addTask="addTaskHeadler"></TodoHeader>
    <TodoMain @delTask="delTaskHeadler" :list="showList"></TodoMain>
    <TodoFooter @changeTask="changeTaskHeadler" :list="showList" @clearTask="clearTaskHeadler"></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list") || "[]"),
      isOk: 0,
    };
  },
  methods: {
    addTaskHeadler(TaskName) {
      this.list.push({
        id: this.list.length > 0 ? this.list[this.list.length - 1].id + 1 : 100,
        name: TaskName,
        isDone: false,
      });
    },
    delTaskHeadler(id) {
      let index = this.list.findIndex((item) => item.id == id);
      this.list.splice(index, 1);
    },
    changeTaskHeadler(isOk) {
      this.isOk = isOk;
    },
    clearTaskHeadler() {
      this.list = this.list.filter((item) => !item.isDone);
    },
  },
  computed: {
    showList() {
      // 根据 isSel 的值来决定筛选什么数据返回
      if (this.isOk === 1) {
        return this.list.filter((item) => !item.isDone);
      } else if (this.isOk === 2) {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list;
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        // 将 this.list 数据存入本地
        localStorage.setItem("list", JSON.stringify(this.list));
      },
    },
  },
};
</script>